#include <Windows.h>
#include <string>
#include <io.h>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;

void getFileNames (string path, vector<string>& files) {
	intptr_t hFile = 0;
	struct _finddata_t fileinfo;
	string p;
	if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
	{
		do{
			if ((fileinfo.attrib & _A_SUBDIR))
			{
				if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
					getFileNames(p.assign(path).append("\\").append(fileinfo.name), files);
			}
			else
			{
				files.push_back(p.assign(path).append("\\").append(fileinfo.name));
			}
		} while (_findnext(hFile, &fileinfo) == 0);
		_findclose(hFile);
	}
}

void search_disk (vector<string>& fileNames) {
	DWORD dwLen = GetLogicalDriveStrings(0, NULL);
	char * pszDriver = new char[dwLen];
	GetLogicalDriveStrings(dwLen, pszDriver);
	
	while(*pszDriver != '\0'){

		string path(pszDriver);
		getFileNames(path, fileNames);
//		for (const auto &ph : fileNames) {
//			cout << ph << "\n";
//		}
		
		pszDriver += strlen(pszDriver) + 1;
	}
}

void build (vector<string>& fileNames) {
	search_disk (fileNames);
}

string split (string s) {
	string res = "";
	int index = -1;
	while (s.find('\\', index + 1) != s.npos) {
		index = s.find('\\', index + 1);
	}
	index += 1;
	for (int i = index; i < s.size(); i ++) {
		res += s[i];
	}
	return res;
}

void search (string key, vector<string>& fileNames, vector<string>& results) {
	for (int i = 0; i < fileNames.size(); i ++) {
		string name = split (fileNames[i]);
		if (name.find(key) != fileNames[i].npos) {
			results.push_back(fileNames[i]);
		}
	}
}

int main () {
	vector<string> fileNames;
	build (fileNames);
	string key;
	string prevkey;
	cout << "READY" << endl;
	ifstream inp;
	while (1) {
		key = "";
		inp.open("C:/RoxyCache/RoxySearch/search.roxycache",ios::in);
		inp >> key;
		inp.close();
		if (key != prevkey) {
			cout << key << endl;
			vector<string> results;
			search (key, fileNames, results);
			ofstream outp;
			outp.open("C:/RoxyCache/RoxySearch/res.roxycache",ios::out);
			for (int i = 0; i < results.size(); i ++) {
				outp << results[i] << endl;
			}
			outp.close();
		}
		prevkey = key;
	}
	return 0;
}
